package com.iee.patterns.example.strategy.invoker;

import com.iee.patterns.example.strategy.invoker.annotion.SocketCmd;
import com.iee.patterns.example.strategy.invoker.annotion.SocketModule;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 *@ClassName Scanner
 *@Description TODO
 *@Author longxiaonan@163.com
 *@Date 2021/6/30 0030 17:03
 */
@Component
public class Scanner implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        Class<?> aClass = bean.getClass();
        Class<?>[] interfaces = aClass.getInterfaces();
        if (interfaces != null && interfaces.length > 0) {
            // 扫描所有的接口
            for (Class<?> interFace : interfaces) {
                SocketModule socketModule = interFace.getAnnotation(SocketModule.class);
                if (Objects.isNull(socketModule)) {
                    continue;
                }
                Method[] methods = interFace.getMethods();
                if (methods != null && methods.length > 0) {
                    for (Method method : methods) {
                        SocketCmd socketCmd = method.getAnnotation(SocketCmd.class);
                        if (Objects.isNull(socketCmd)) {
                            continue;
                        }
                        short module = socketModule.module();
                        short cmd = socketCmd.cmd();
                        Invoker invoker = Invoker.valueOf(bean, method);
                        if (InvokerHolder.getInvoker(module, cmd) == null) {
                            InvokerHolder.addInvoker(module, cmd, invoker);
                        } else {
                            System.out.println("重复注册执行器module: " + module + "    cmd: " + cmd);
                        }
                    }
                }
            }
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

}
